package cn.sfrog.project.biz.admin.service.impl;

import cn.sfrog.common.constant.ConfigConstants;
import cn.sfrog.common.constant.Constants;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.core.domain.model.LoginUser;
import cn.sfrog.common.core.redis.RedisCache;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.framework.web.service.TokenService;
import cn.sfrog.project.biz.admin.domain.BizUserAccount;
import cn.sfrog.project.biz.admin.domain.BizUserWithdrawRecord;
import cn.sfrog.project.biz.admin.domain.vo.BizUserWithdrawRecordFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserWithdrawRecordQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserWithdrawRecordVO;
import cn.sfrog.project.biz.admin.enums.BizUserTradeTypeEnum;
import cn.sfrog.project.biz.admin.mapper.BizUserWithdrawRecordMapper;
import cn.sfrog.project.biz.admin.service.IBizUserTradeRecordService;
import cn.sfrog.project.biz.admin.service.IBizUserWithdrawRecordService;
import cn.sfrog.project.biz.web.vo.account.AppUserApplyWithdrawFormVO;
import cn.sfrog.system.domain.vo.BizAuditVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.mapper.SysUserMapper;
import cn.sfrog.system.service.ISysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 用户提现记录Service业务层处理
 */
@Service
public class BizUserWithdrawRecordServiceImpl extends ServiceImpl<BizUserWithdrawRecordMapper, BizUserWithdrawRecord> implements IBizUserWithdrawRecordService {
    @Resource
    private BizUserWithdrawRecordMapper bizUserWithdrawRecordMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBizUserTradeRecordService bizUserTradeRecordService;
    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询用户提现记录
     *
     * @param id 用户提现记录主键
     * @return 用户提现记录
     */
    @Override
    public BizUserWithdrawRecordVO selectBizUserWithdrawRecordById(Long id) {
        return bizUserWithdrawRecordMapper.selectBizUserWithdrawRecordById(id);
    }

    /**
     * 查询用户提现记录列表
     *
     * @param query 用户提现记录
     * @return 用户提现记录
     */
    @Override
    public List<BizUserWithdrawRecordVO> selectBizUserWithdrawRecordList(BizUserWithdrawRecordQueryVO query) {
        return bizUserWithdrawRecordMapper.selectBizUserWithdrawRecordList(query);
    }

    /**
     * 新增用户提现记录
     *
     * @param form 用户提现记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizUserWithdrawRecord(BizUserWithdrawRecordFormVO form) {
        BizUserWithdrawRecord bizUserWithdrawRecord = new BizUserWithdrawRecord();
        BeanUtils.copyProperties(form, bizUserWithdrawRecord);
        bizUserWithdrawRecord.setCreateTime(new Date());
        bizUserWithdrawRecord.setCreateBy(SecurityUtils.getUsername());
        bizUserWithdrawRecord.setUpdateTime(new Date());
        bizUserWithdrawRecord.setUpdateBy(SecurityUtils.getUsername());
        return bizUserWithdrawRecord.insert();
    }

    /**
     * 修改用户提现记录
     *
     * @param form 用户提现记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizUserWithdrawRecord(BizUserWithdrawRecordFormVO form) {
        BizUserWithdrawRecord bizUserWithdrawRecord = new BizUserWithdrawRecord();
        BeanUtils.copyProperties(form, bizUserWithdrawRecord);
        bizUserWithdrawRecord.setUpdateTime(new Date());
        bizUserWithdrawRecord.setUpdateBy(SecurityUtils.getUsername());
        return bizUserWithdrawRecord.updateById();
    }

    /**
     * 批量删除用户提现记录
     *
     * @param ids 需要删除的用户提现记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizUserWithdrawRecordByIds(Long[] ids) {
            return BizUserWithdrawRecord.DAO.delete(Wrappers.lambdaQuery(BizUserWithdrawRecord.class).in(BizUserWithdrawRecord::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
        //return BizUserWithdrawRecord.DAO.update(Wrappers.lambdaUpdate(BizUserWithdrawRecord.class).in(BizUserWithdrawRecord::getId, (Object[]) vo.getIds()).set(BizUserWithdrawRecord::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public int audit(BizAuditVO auditVO) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        BizUserWithdrawRecord record = BizUserWithdrawRecord.DAO.selectById(auditVO.getId());
        record.setAuditStatus(auditVO.getAuditStatus());
        record.setAuditTime(DateUtils.getNowDate());
        record.setAuditUserId(userId);
        record.setAuditRemark(auditVO.getRemark());
        boolean update = record.updateById();
        LambdaQueryWrapper<BizUserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                .eq(BizUserAccount::getUserId,record.getUserId());
        BizUserAccount bizUserAccount = BizUserAccount.DAO.selectOne(lambdaQueryWrapper);
        if(Constants.AUDIT_STATUS_SUCCESS.equals(auditVO.getAuditStatus())){
            //审核通过,扣减账户余额，并把冻结金额扣减,提现金额增加
            bizUserAccount.setCommissionAmount(bizUserAccount.getCommissionAmount().subtract(record.getWithdrawEscortCount()));
            bizUserAccount.setFreezeAmount(bizUserAccount.getFreezeAmount().subtract(record.getWithdrawEscortCount()));
            bizUserAccount.setWithdrawAmount(bizUserAccount.getWithdrawAmount().add(record.getWithdrawEscortCount()));
            bizUserAccount.updateById();
            //SysUser dbUser = sysUserMapper.selectUserById(bizUserAccount.getUserId());
            SysUser sysUser = new SysUser();
            sysUser.setUserId(bizUserAccount.getUserId());
            sysUser.setEscortBeanCount(bizUserAccount.getAccountBalance().add(bizUserAccount.getGiveAwayAmount()).add(bizUserAccount.getCommissionAmount()));
            sysUserMapper.updateUser(sysUser);
            //提现成功了 才会记录交易记录
            bizUserTradeRecordService.saveUserTradeRecord(record.getUserId(),record.getWithdrawEscortCount().negate(), BizUserTradeTypeEnum.WITHDRAW.getCode(),record.getSerialNumber(),"提现");
        }else {
            //如果审核拒绝  冻结金额释放
            bizUserAccount.setFreezeAmount(bizUserAccount.getFreezeAmount().subtract(record.getWithdrawEscortCount()));
            bizUserAccount.updateById();
        }
        return update ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean applyWithdraw(AppUserApplyWithdrawFormVO form) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        LambdaQueryWrapper<BizUserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<BizUserAccount>()
                .eq(BizUserAccount::getUserId,user.getUserId());
        BizUserAccount bizUserAccount = BizUserAccount.DAO.selectOne(lambdaQueryWrapper);
        BigDecimal subCommissionAmount = bizUserAccount.getCommissionAmount();
        //2022-10-27修改 提现仅限于提成赚到的钱，即提成金额。需要减掉冻结金额
        BigDecimal ableAmount = bizUserAccount.getCommissionAmount().subtract(bizUserAccount.getFreezeAmount());
        if(form.getWithdrawAmount().compareTo(ableAmount) == 1){
            throw new ApiException("提现金额大于账户可提现金额，不可提现");
        }
        //提现记录
        BizUserWithdrawRecord record = new BizUserWithdrawRecord();
        record.setUserId(user.getUserId());
        record.setBankCardId(form.getBankCardId());
        record.setWithdrawEscortCount(form.getWithdrawAmount());
        //计算实际人民币金额
        String s = sysConfigService.selectConfigByKey(ConfigConstants.ESCORT_BEAN_EXCHANGE_SCALE);
        BigDecimal x = new BigDecimal(s);
        BigDecimal y = new BigDecimal(1);
        BigDecimal scale = y.divide(x, 1, BigDecimal.ROUND_CEILING);
        BigDecimal realRMBAmount = (form.getWithdrawAmount().multiply(scale)).setScale(0, BigDecimal.ROUND_DOWN);
        record.setWithdrawAmount(realRMBAmount);

        record.setAccountBalance(subCommissionAmount.subtract(form.getWithdrawAmount()));
        record.setWithdrawTime(DateUtils.getNowDate());
        record.setSerialNumber(redisCache.buildWithdrawSerialNumber());
        boolean insert = record.insert();
        if(insert){
            //更新用户账户表
            bizUserAccount.setFreezeAmount(bizUserAccount.getFreezeAmount().add(form.getWithdrawAmount()));
            bizUserAccount.updateById();
//            user.setEscortBeanCount(bizUserAccount.getAccountBalance().add(bizUserAccount.getGiveAwayAmount()));
//            sysUserMapper.updateUser(user);
//            loginUser.setUser(user);
//            tokenService.refreshToken(loginUser);

        }
        return insert;
    }
}
